<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryFormRef" label-width="auto">
      <!-- 第一行：名称、分类、搜索、重置 -->
      <el-row style="margin-top: 8px;">
        <el-col :xs="24" :sm="12" :md="6">
          <el-form-item label="物流公司名称:" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
        </el-col>
        
        <el-col :xs="24" :sm="12" :md="6">
          <el-form-item label="物流公司分类:" prop="logisticsClass">
            <el-select
              v-model="queryParams.logisticsClass"
              placeholder="请选择物流公司分类"
              clearable
              class="!w-240px"
            >
              <el-option v-for="item in logisticsClass" :key="item" :label="item" :value="item"/>
            </el-select>
          </el-form-item>
        </el-col>


        <el-col :xs="24" :sm="12" :md="6">
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button plain class="blue-btn" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 第二行：新增、编辑、删除按钮 -->
      <el-row style="margin-top: 8px;">
        <el-col :span="24">
          <div style="display: flex; flex-wrap: wrap; gap: 12px;">
            <el-button type="primary" @click="openForm('create')">新增</el-button>
            <el-button plain class="blue-btn" @click="handleEdit">编辑</el-button>
            <el-button plain class="blue-btn red-hover" @click="handleBatchDelete">删除</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :header-cell-style="{ 'background-color': '#f2f2f2', 'color': '#333' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :header-cell-style="{ padding: '0', 'vertical-align': 'middle' }"
        :cell-style="{ padding: '0', 'vertical-align': 'middle' }"
      />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="物流公司编码" align="center" prop="code" />
      <el-table-column label="物流公司名称" align="center" prop="name" >
      <template #default="scope">
        <el-link type="primary" @click="goToContact(scope.row.id)">
          {{ scope.row.name }}
        </el-link>
      </template>
      </el-table-column>
      <el-table-column label="物流公司分类" align="center" prop="logisticsClass" />
      <el-table-column label="经营范围" align="center" prop="scope" />
      <el-table-column label="公司规模" align="center" prop="scale" />
      <el-table-column label="公司电话" align="center" prop="phone" />
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <LogistCompanyForm 
    ref="formRef" 
    @success="getList" 
    :logistics-class-options="logisticsClass"  
  />
</template>

<script setup lang="ts">
import { LogistCompanyApi, LogistCompanyVO } from '@/api/busipart/logistcompany'
import LogistCompanyForm from './LogistCompanyForm.vue'

defineOptions({ name: 'LogistCompany' })

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const list = ref<LogistCompanyVO[]>([])
const total = ref(0)
const selectedRows = ref<LogistCompanyVO[]>([]) // 存储选中行
//下拉选项
const logisticsClass = ref<string[]>([])

/** 加载下拉选项数据 */
const loadDropdownOptions = async () => {
  try {
    const [
      logisticsData,
    ] = await Promise.all([
      LogistCompanyApi.getLogisticsClass(),
    ])
    logisticsClass.value = Array.isArray(logisticsData) ? logisticsData : []
  } catch (error) {
    console.error('加载下拉选项失败:', error)
  }
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  logisticsClass: undefined,
})

const queryFormRef = ref()
const formRef = ref()

// ********************物流公司跳转路由*******************
import { useRouter } from 'vue-router'

const router = useRouter()


const goToContact = (id: number) => {
  router.push({
    path: '/busi_part/busipart/logistcompany/LogistContactEdit',
    query: { id }
  })
}

import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { getLogistContacts } from '@/api/busipart/logistcompany'

const route = useRoute()
const contactList = ref([])

onMounted(async () => {
  const logistId = route.query.logistId
  if (logistId) {
    const res = await getLogistContacts(logistId as string)
    contactList.value = res || []
  }
})


// **********物流公司跳转路由*******************


/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await LogistCompanyApi.getLogistCompanyPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加操作 */
const openForm = (type: string, data?: any) => {
  formRef.value.open(type, data)
}

/** 选择项变化 */
const handleSelectionChange = (selection: LogistCompanyVO[]) => {
  selectedRows.value = selection
}

/** 编辑操作：只能选中一项 */
const handleEdit = async () => {
  if (selectedRows.value.length !== 1) {
    message.warning('请选择一条要编辑的记录')
    return
  }
  const id = selectedRows.value[0].id
  // 请求后端获取详情
  const detail = await LogistCompanyApi.getLogistCompany(id)
  formRef.value.open('edit', detail) // 传完整数据给表单
}


/** 批量删除操作 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    message.warning('请选择要删除的记录')
    return
  }
  try {
    await message.delConfirm('确定删除所选记录吗？')
    const ids = selectedRows.value.map(item => item.id)
    await LogistCompanyApi.deleteLogistCompany(ids)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 初始化 */
onMounted(() => {
  loadDropdownOptions()
  getList()
})

// 页面重新进入时自动刷新数据
onActivated(() => {
  getList()
})
</script>

<style scoped>
/* 表头 checkbox 居中：Element Plus 特有类 */
::v-deep(.el-table .el-table-column--selection .cell) {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  padding: 0;
}

.blue-btn {
  border: 1px solid #409eff;
  color: #409eff;
  background-color: white;
  transition: all 0.3s ease;
}

.blue-btn:hover {
  background-color: #409eff;
  color: white;
}

.red-hover {
  border-color: #409eff;
  color: #409eff;
  background-color: white;
  transition: all 0.3s ease;
}

.red-hover:hover {
  background-color: #ff4d4f;
  color: white;
  border-color: #ff4d4f;
}
</style>
